/**
 * Created by Dalyn on 2017/3/22.
 */
import React, {Component}from 'react';
import Relay from "react-relay";
import "./css/settlement.css"
import InputBox from "../../common/InputBox";
import Confirm from "../../common/Confirm";
import GetQiNiuToken from "./mutation/GetQiNiuToken"
import ExamineEnBalanceMutation from "./mutation/ExamineEnBalanceMutation"


import {_Modal,_Icon} from 'ANT_DE';
const Modal = _Modal,
       Icon = _Icon;

export default class ExamineBomb extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            displayflag: true,
            partyAEnid: "",
            partyBEnid: "",
            partyBEnids: "",
            maxMoney: "",
            ratio: "",
            upperLimit: "",
            loanRatio: "",
            dayRate: "",
            token:"",
            hint:"",
            /**/
            isUpload:false,
        };
        this.style = {
            confirm: {
                width: '60px',
                height: '30px',
                backgroundColor: "#1b3249",
                fontSize: "18px",
                color: "#fff",
                marginTop: "16px",
                marginLeft: "20px",
                fontFamily: "Microsoft YaHei"
            },
            upload: {
                width: '100px',
                height: '30px',
                backgroundColor: "#fff",
                fontSize: "12px",
                color: "#000",
                marginTop: "16px",
                marginLeft: "50px",
                fontFamily: "Microsoft YaHei",
                border:"1px solid #9AFF70"
            },
            upperLimit: {
                width: "120px",
                height: "22px",
                marginTop: "10px"
            },
        };
        this.isshow = 'none';
        this.isRelay = true;
        this.normalType = ".jpeg|.png|.bmp|.jpg|.gif";
    }

    componentWillMount() {

    }

    success(invoiceImg,orderId) {
        this.props._success(invoiceImg,orderId);
    }

    relayApply() {
        Relay.Store.commitUpdate(
            new ExamineEnBalanceMutation({
                orderId: this.state.orderId,
                status: this.state.status,
                invoiceImg: this.state.invoiceImg,
            }),
            {
                onFailure: () => {
                    console.log("请求失败")
                },
                onSuccess: (response) => {
                    let data = response.examineEnBalance.data;
                    if (data.errorCode === "0") {
                        /*请求成功-弹框隐藏-传递图片链接、订单id*/
                        this.setState({
                            displayflag: true,
                        }, this.success(data.enterpriseBalance.invoiceImg,data.enterpriseBalance.orderId));
                    } else {
                        this.setState({
                            hint: data.value
                        });
                    }
                }

            }
        );
    }
    /*上传文件*/
    upload(){
        let myfile = document.getElementById('choiceFile').files[0];
        if(myfile){
            //校验文件格式
            let fileType = myfile.name;
            let trueFileType = myfile.name;
            let fileName = myfile.name;
            if(null != myfile.name && myfile.name.indexOf(".") != -1){
                trueFileType = fileType.substr(fileType.lastIndexOf("."));
                fileType = trueFileType.toLowerCase();
                fileName = fileName.substr(0,fileName.lastIndexOf("."));
            }
            if(fileName.indexOf("%") > -1){
                this.setState({
                    hint: "上传的文件名错误，不能包含%"
                })
                return;

            }
            if (this.normalType.indexOf(fileType) == -1) {
                this.setState({
                    hint: "上传的文件格式错误"
                })
                return;
            }
            //校验文件的大小
            let maxSize = 8388608;
            if(myfile.size > maxSize){
                this.setState({
                    hint:"上传的文件大小不能超过8M"
                })
                return ;
            }
            let name = myfile.name;
            Relay.Store.commitUpdate(
                new GetQiNiuToken({}), {
                    onSuccess: (res) => {
                        let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                        if(errorCode==0){
                            let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken
                            this.token = qiniutoken;
                            /*this.upLoadFile(myfile,qiniutoken,name);*/
                            /**发票文件名用订单号，防止重复*/
                            /*console.log(this.props._orderId+"_发票"+trueFileType);*/
                            this.upLoadFile(myfile,qiniutoken,this.props._orderId+"_balance"+trueFileType);
                        }
                    }
                }
            )
        }else {
            this.setState({
                hint:"请选择上传的文件"
            })
        }
    }
    upLoadFile(file,token,name) {
        let upLoadUrl = "http://up-z2.qiniu.com";
        let xhr = new XMLHttpRequest();
        xhr.open("POST", upLoadUrl, true);
        let formData = new FormData();
        formData.append('file',file);
        formData.append('token',token);
        formData.append('key',name);
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    let responseText = JSON.parse(xhr.responseText);
                    this.setState({
                        orderId: this.props._orderId,
                        status: parseFloat(this.props._statusItem)+1,
                        invoiceImg: responseText.key,
                    }, this.relayApply);
                } else {
                    this.setState({
                        hint:"上传失败"
                    })
                }
            }
        };
        xhr.send(formData);
    }

    /*点击确认*/
    handleConfirm(flag) {
        // console.log(flag);
        if(flag){
            this.upload();
        }
        this.setState({
            isUpload:false
        })
    }

    /*点击取消*/
    handleCancel(flag) {
        this.setState({
            displayflag: !flag
        });
    }

    /*交易文件*/
    checkFile(){
        let myfile = document.getElementById('choiceFile').files[0];
        if(myfile) {
            //校验文件格式
            let fileType = myfile.name;
            let fileName = myfile.name;
            if(null != myfile.name && myfile.name.indexOf(".") != -1){
                fileType = fileType.substr(fileType.lastIndexOf(".")).toLowerCase();
                fileName = fileName.substr(0,fileName.lastIndexOf("."));
            }
            // console.log(fileName);
            if(fileName == "%"){
                this.setState({
                    hint: "上传的文件名错误，不能为%",
                    isUpload:false
                })
                return;
            }
            if (this.normalType.indexOf(fileType) == -1) {
                this.setState({
                    hint: "上传的文件格式错误",
                    isUpload:false
                })
                return;
            }
            //校验文件的大小
            let maxSize = 8388608;
            if (myfile.size > maxSize) {
                this.setState({
                    hint: "上传的文件大小不能超过8M",
                    isUpload:false
                })
                return;
            }
        }
        this.claerHint();
    }

    /*初始化数据*/
    initHit(){
        var obj = document.getElementById('choiceFile') ;
        let myfile = document.getElementById('choiceFile').files[0];
        if(myfile){
            obj.outerHTML=obj.outerHTML;
        }
        this.claerHint();
    }

    /*清空提醒信息*/
    claerHint(){
        this.setState({
            hint:"",
            isUpload:true
        })
    }

    //asdasdsdasdasd
    render() {
        return (
        <Modal
            className="modal_gre-title"
            visible={!this.state.displayflag}
            title="审核"
            onCancel={this.handleCancel.bind(this, this.state.displayflag)}
            onOk={this.handleConfirm.bind(this, this.state.isUpload)}
        >
                <div className="clear">
                    <div className="settle_set_up clear">
                        <div className="settle_set_upload">
                            <label  className="settle_set_uplabel">上传发票:</label>
                            <input  className="settle_set_upinputo" type="file" onChange={this.checkFile.bind(this)} id="choiceFile"  ref={'_upload'}/>
                        </div>
                        <p className="settle_set_loadp">请拍照或扫描上传收到的纸质发票支持png,jpg,bmp,gif格式文件</p>
                    </div>
                    <div className="settle_set_hint1">{this.state.hint}</div>
                </div>
        </Modal>
        )
    }
}